package controllers

import (
	"github.com/astaxie/beego"
	"html/template"
	"src/gitee.com/wx_e6924dbcd0/notebook/models"
	"strconv"
)

type LinkMainController struct {
	beego.Controller
}

func (c *LinkMainController) LinkPage() {
	c.TplName = "link_admin.html"
}

/**
 * 获取信息根据用户名
 */
//http://127.0.0.1:8080/linklist?name=admin
func (c *LinkMainController) LinkList() {
	//防xss
	name := template.HTMLEscapeString(c.Input().Get("name"))
	//获取列表
	if name != "" {
		result := make(map[string]interface{})
		LinktList, err := models.GetLinkList(name)
		if err != nil {
			log := models.UitlLog()
			log.Error("GetLinkList err" + err.Error())
			return
		}
		result["LinktList"] = LinktList
		c.Data["json"] = result
		c.ServeJSON()
		return
	}
}

/**
 * 联系管理员或发送内容
 */
//http://127.0.0.1:8080/link?sender=admin&accepter=ii&content=我不
func (c *LinkMainController) DoLink() {
	sender := template.HTMLEscapeString(c.Input().Get("sender"))
	accepter := template.HTMLEscapeString(c.Input().Get("accepter"))
	content := template.HTMLEscapeString(c.Input().Get("content"))
	if content != "" && sender != "" && accepter != "" {
		// orm insert 存储
		OneL, err := models.GoLink(sender, accepter, content)
		if err != nil {
			log := models.UitlLog()
			log.Error("GoLink err" + err.Error())
			return
		}
		c.Data["json"] = OneL
		c.ServeJSON()
	}
	return
}

/**
 * 根据ID取消
 */
//http://127.0.0.1:8080/delcomment?c_id=1
func (c *LinkMainController) DelLinkComment() {
	// 读取数据库内容
	// 引用model,->orm
	// orm -> 引用 conf 配置连接DB
	// orm 读取数据库
	idstr := template.HTMLEscapeString(c.Input().Get("id"))
	id, errc := strconv.Atoi(idstr)
	if errc != nil {
		log := models.UitlLog()
		log.Error("int64类型转换错误" + errc.Error())
		return
	}
	result := make(map[string]interface{})
	//执行删除操作
	num, err := models.DoDelLinkComment(int64(id))
	if err != nil {
		log := models.UitlLog()
		log.Error("DoDelLinkComment err" + errc.Error())
		return
	}
	// 成功返回数据
	result["count"] = num
	result["DelCri"] = "成功！"
	c.Data["json"] = result
	c.ServeJSON()
}

/**
 * 根据评论ID修改状态值
 */
//http://127.0.0.1:8080/uplinksta?id=2&sta=1
func (c *LinkMainController) UpLinkSta() {
	idstr := template.HTMLEscapeString(c.Input().Get("id"))
	id, errc := strconv.Atoi(idstr)
	if errc != nil {
		log := models.UitlLog()
		log.Error("int64类型转换错误" + errc.Error())
		return
	}
	sta_id := template.HTMLEscapeString(c.Input().Get("sta"))
	sta, errc := strconv.Atoi(sta_id)
	if errc != nil {
		log := models.UitlLog()
		log.Error("int64类型转换错误" + errc.Error())
		return
	}
	//result := make(map[string]interface{})
	err := models.UpSta(int64(id), int64(sta))
	if err != nil {
		//result["TmbUp"] = "AddMessage failed" + err.Error()
		log := models.UitlLog()
		log.Error("UpSta failed" + errc.Error())
		return
	}
	c.Data["json"] = "成功！"
	c.ServeJSON()
	return
}
